﻿using System;
using System.Configuration;

namespace Middleware.Server
{
    public class ServiceBase
    {
        private bool _running;
        private readonly string _ip;
        private readonly int _port;
        private ServerRequestHandler _srh;

        protected ServiceBase() {
            _ip = ConfigurationSettings.AppSettings["ip"];
            _port = Convert.ToInt32(ConfigurationSettings.AppSettings["port"]);
        }

        public ServiceBase(string ip, int port) {
            this._ip = ip;
            this._port = port;
        }

        private void Open() {
            _srh = new ServerRequestHandler(this._ip, this._port);
            _srh.Open();
        }

        public void Start() {
            this.Open();
            this._running = true;
            while (_running) {
                byte[] requestArray = _srh.Receive();
                byte[] result = Invoker.Invoke(requestArray);
                if (result != null) {
                    _srh.Send(result);
                }
            }
        }

        public void Close() {
            _srh.Close();
        }
    }
}
